package com.inwavetech.os.util;

import java.sql.SQLException;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.preference.PreferenceManager;

import com.inwavetech.os.LoginActivity;
import com.inwavetech.os.entity.User;
import com.j256.ormlite.dao.Dao;


public class SessionManager {

    private final Dao userDao;

    // Shared Preferences
    SharedPreferences pref;

    // Editor for Shared preferences
    Editor editor;

    // Context
    Context _context;

    // Sharedpref file name
    private static final String PREF_NAME = "com.inwavetech.os";

    // All Shared Preferences Keys
    private static final String IS_LOGIN = "IsLoggedIn";

    // User name (make variable public to access from outside)
    public static final String KEY_NAME = "name";

    // Email address (make variable public to access from outside)
    public static final String KEY_TOKEN = "token";
    private Object username;
    private User user;

    // Constructor
    public SessionManager(Context context, DaoHelper daoHelper){
        this._context = context;
        this.userDao = daoHelper.getDao(User.class);

        pref = _context.getSharedPreferences(PREF_NAME, Context.MODE_MULTI_PROCESS);
        editor = pref.edit();
    }

    /**
     * Create login session
     * */
    public void createLoginSession(String name, String token) throws SessionManagerException {

        // store the user on db
        try {
            storeUser(name);
        } catch (SQLException e) {
            throw new SessionManagerException("could not store the user due to a database error");
        }

        // Storing login value as TRUE
        editor.putBoolean(IS_LOGIN, true);

        // Storing name in pref
        editor.putString(KEY_NAME, name);

        // Storing email in pref
        editor.putString(KEY_TOKEN, token);

        // commit changes
        editor.commit();
    }

    /**
     * Check login method wil check user login status
     * If false it will redirect user to login page
     * */
    public boolean checkLogin(){
        // get the login status
        boolean loginStatus = this.isLoggedIn();

        if(!loginStatus){
            // user is not logged in redirect him to Login Activity
            Intent i = new Intent(_context, LoginActivity.class);
            // Closing all the Activities
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

            // Add new Flag to start new Activity
            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

            // Staring Login Activity
            _context.startActivity(i);
        }

        return loginStatus;
    }

    /**
     * Clear session details
     * */
    public void logoutUser(){
        // Clearing all data from Shared Preferences
        editor.clear();
        editor.commit();

        // After logout redirect user to Loing Activity
        Intent i = new Intent(_context, LoginActivity.class);
        // Closing all the Activities
        i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        // Add new Flag to start new Activity
        i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

        // Staring Login Activity
        _context.startActivity(i);
    }

    /**
     * Quick check for login
     * **/
    // Get Login State
    public boolean isLoggedIn(){
        return pref.getBoolean(IS_LOGIN, false);
    }

    public String getUsername() {
        return pref.getString(KEY_NAME, null);
    }

    public String getToken() {
        return pref.getString(KEY_TOKEN, null);
    }

    public User getUser() throws SessionManagerException {
        User user = null;

        try {
            user = (User) userDao.queryForId(pref.getString(KEY_NAME, null));
        } catch (SQLException e) {
            throw new SessionManagerException("the user could not be restored due to a database error");
        }

        return user;
    }

    public class SessionManagerException extends Exception {
        public SessionManagerException(String s) {
            super(s);
        }
    }

    private void storeUser(String username) throws SQLException {
        User user = (User) userDao.queryForId(username);

        if (user == null) {
            user = new User();
            user.username = username;
            userDao.create(user);
        }
    }
}